﻿using System;
using Newtonsoft.Json.Linq;

namespace PlurkApi
{
    /// <summary>
    ///  The data returned by getActive and getHistory can be of following nature: 
    /// 
    ///  Friendship request:
    ///  {"type": "friendship_request", "from_user": {"nick_name": ...}, "posted": ...}
    ///  
    ///  Friendship pending:
    ///  {"type": "friendship_pending", "to_user": {"nick_name": ...}, "posted": ...}
    ///  
    ///  New fan notification: (does not require actions from the user)
    /// {"type": "new_fan", "new_fan": {"nick_name": ...}, "posted": ...}
    ///  
    /// Friendship accepted notification: (does not require actions from the user)
    /// {"type": "friendship_accepted", "friend_info": {"nick_name": ...}, "posted": ...}
    /// 
    /// New friend notification: (does not require actions from the user)
    /// {"type": "new_friend", "new_friend": {"nick_name": ...}, "posted": ...} 
    /// </summary>
    public class alert
    {
        /// <summary>
        /// alert type: friendship_request, friendship_pending, new_fan, friendship_accepted, new_friend
        /// </summary>
        public string type { get; set; }

        /// <summary>
        /// posted time
        /// </summary>
        public DateTime posted { get; set; }

        /// <summary>
        /// user information about the alert 
        /// </summary>
        public user_info user_info { get; set; }

        /// <summary>
        /// Initializes a new instance of the <see cref="alert"/> class.
        /// </summary>
        /// <param name="jsonString">The json string.</param>
        public alert(string jsonString)
        {
            var obj = JObject.Parse(jsonString);
            if(obj.Count <= 0){ return;}

            type = (obj["type"] == null) ? string.Empty : (string)obj["type"];

            if (obj["from_user"] != null)
            {
                user_info = new user_info(obj["from_user"].ToString());
            }
            else if (obj["to_user"] != null)
            {
                user_info = new user_info(obj["to_user"].ToString());
            }
            else if (obj["new_fan"] != null)
            {
                user_info = new user_info(obj["new_fan"].ToString());
            }
            else if (obj["friend_info"] != null)
            {
                user_info = new user_info(obj["friend_info"].ToString());
            }
            else if (obj["new_friend"] != null)
            {
                user_info = new user_info(obj["new_friend"].ToString());
            }

            if (obj["posted"] != null) { posted = DateTime.Parse(obj["posted"].ToString().Replace("\"", "")); }   
        }
    }
}